<template>
  <view class="">
    <view class="progress-container">
      <view class="top_box">
        <view style="margin-bottom: 20rpx;line-height: 60rpx;text-align: center;width: 50%;margin-left: 175rpx;">
          <text>运输</text>
        </view>
        <view style="margin-bottom: 20rpx;">
          <text style="margin-bottom: 20rpx;line-height: 60rpx;font-size: 20rpx;" @click="wde()">我的运单</text>
        </view>
      </view>
      <uni-steps
          :options="[{title: '已抢单'}, {title: '已领票'}, {title: '已到矿'}, {title: '已装车'},{title: '已卸车'}]"
          :active="status"></uni-steps>
    </view>
    <view v-if="ss">
      <view class="container" v-if="status == 0">
        <view
            style="text-align: center;font-size: 20rpx; height: 50rpx;line-height: 50rpx;color: #ffaa00;background-color: #fcf3ed;">
          请在{{ countdownText }}内领取提货单，否则运单将取消
        </view>
        <view class="center_box">
          <image :src="or.qrcode"></image>
        </view>

      </view>
      <view class="container" v-if="status == 1">
        <view class="center_box">
          <text>请前往装货点，完成到矿打卡</text>
          <view
              style="width: 300rpx; height: 300rpx; background-color: #002f93;margin-top: 30rpx; border-radius: 50%; display: flex; flex-direction: column; justify-content: center; align-items: center;"
              @click="daka()">
            <view style="font-size: 40rpx; color: #fff;">打卡</view>
            <view style="font-size: 40rpx; color: #fff; margin-top: 30rpx;">{{ countdownText }}</view>
          </view>
        </view>
      </view>
      <view class="container" v-if="status == 2">
        <view class="center_box">
          <view>请在完成后，进行装车确认</view>
          <image src="/static/zhuangche.png" mode="" style="width: 500rpx;margin-top: 20rpx;"></image>
        </view>
      </view>
      <view class="container" v-if="status == 3">
        <view class="center_box">
          <view>请在完成后，进行卸车确认</view>
          <image src="/static/zhuangche.png" mode="" style="width: 500rpx;margin-top: 20rpx;">二维码</image>
        </view>
      </view>
      <view class="container" v-if="status == 4">
        <view class="center_box">
          <view>请在完成后，进行卸车确认</view>
          <image src="/static/zhuangche.png" mode="" style="width: 500rpx;margin-top: 20rpx;"></image>
        </view>
      </view>
      <view class="xinxi">
        <view class="xunh">
          <view class="yaodong">
            <view class="zuo">
              <image src="/photo/zhaohuo/diandian.png" mode=""
                     style="width: 40rpx;height: 80rpx;margin-top: 17rpx;"></image>
            </view>
            <view class="you">
              <view style="font-size: 28rpx;height: 70rpx;">
                {{ goodsDetails.shipping_station_name }} - {{ goodsDetails.shipping_station_address }}
              </view>
              <view style="font-size: 28rpx;height: 70rpx;">
                {{ goodsDetails.unloading_station_name }} - {{ goodsDetails.unloading_station_address}}
              </view>
            </view>
          </view>
          <view class="yuan">
            <image src="@/photo/zhaohuo/naoz.png" style="width: 27rpx;height: 27rpx;" mode=""></image>
            原煤{{goodsDetails.sum}}吨
          </view>
        </view>
      </view>
      <view class="bottom_box">
        <view style="display: flex;flex-direction: column;text-align: center; margin: 10rpx;">
          <image src="/static/联系.png" mode="" style="height: 50rpx; width: 50rpx;margin: auto;">
          </image>
          <text style="font-size: 20rpx;">联系开票</text>
        </view>
        <view style="display: flex;flex-direction: column;text-align: center;"
              v-if="status ==0 || status ==1 || status ==2 " @click="jump(5)">
          <image src="/static/取消.png" mode="" style="height: 50rpx; width: 50rpx;margin: auto;">
          </image>
          <text style="font-size: 20rpx;" >取消运单</text>
        </view>
        <view style="display: flex;flex-direction: column;text-align: center;">
          <image src="/static/异常.png" mode="" style="height: 50rpx; width: 50rpx;margin: auto;">
          </image>
          <text style="font-size: 20rpx;">异常上报</text>
        </view>
        <view>
          <navigator :url="`/pages/sourceDetails/sourceDetails?id=${or.id}`">
            <button
                style="height: 60rpx; font-size: 24rpx;
                border-radius: 30rpx;border: 1px solid #002f93;color: #002f93;">
              详情
            </button>
          </navigator>
        </view>
        <view v-if="status == 2">
          <navigator :url="`/pages/uploadPhoto/uploadPhoto?id=${or.id}`">
            <button
                style="height: 60rpx; font-size: 24rpx; width: 170rpx;border-radius: 30rpx;border: 1px solid #002f93;color: #fff;background-color: #002f93;">
              装车确认
            </button>
          </navigator>
        </view>
        <view v-if="status == 3">
          <navigator :url="`/pages/unloadCar/unloadCar?id=${or.id}`">
            <button
                style="height: 60rpx; font-size: 24rpx; width: 170rpx;border-radius: 30rpx;border: 1px solid #002f93;color: #fff;background-color: #002f93;">
              卸车确认
            </button>
          </navigator>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import {
  ref,
  reactive,
  onMounted,
  nextTick,
} from 'vue';
import {
  onLoad,
  onShow
} from '@dcloudio/uni-app';
//引入存放jwt的容器
import {
  tokenStore
} from '@/stores/token';
//存放用户信息的容器
import {
  userStore
} from '@/stores/user';
//引入拦截器
import '@/config/requst.js'
import {
  http
} from '@/config/requst.js';

const status = ref(0)
const ss = ref(false)
// 响应式状态
const activeIndex = ref(1)
const progressWidth = ref(0)
const or = ref({})
const goodsDetails = ref({})
const createTime = ref()
const countdownText = ref('02:00:00')
let timer = null
//打卡需要的变量
const da = ref(false)
const change = () => {
  if (this.active < this.list1.length - 1) {
    this.active += 1
  } else {
    this.active = 0
  }
}
//跳转到我的运单界面
const wde = () => {
  uni.navigateTo({
    url: '/pages/yundan/yundan'
  })
}
// 启动倒计时
const startCountdown = (createTime) => {
  const endTime = createTime + 7200 * 1000 // 创建时间 + 2小时（毫秒）
  const update = () => {
    const now = Date.now()
    const remaining = endTime - now
    if (remaining <= 0) {
      countdownText.value = '00:00:00'
      handleTimeout()
      clearTimer()
      return
    }
    countdownText.value = formatTime(remaining)
  }

  // 立即执行一次避免初始延迟
  update()
  timer = setInterval(update, 1000)
}

// 格式化时间
const formatTime = (ms) => {
  const totalSeconds = Math.floor(ms / 1000)
  const hours = Math.floor(totalSeconds / 3600)
  const minutes = Math.floor((totalSeconds % 3600) / 60)
  const seconds = totalSeconds % 60

  const pad = (n) => String(n).padStart(2, '0')
  return `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`
}

// 处理超时
const handleTimeout = () => {
  if (status.value == 0) {
    up(5, "订单已超时")
    or.value = {}
    status.value = ''
    // 这里可以调用关闭订单的接口
    setTimeout(() => {
      uni.switchTab({
        url: '/pages/Search/Search'
      });
    }, 2000);
  }
}

// 清除定时器
const clearTimer = () => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}
const cha = async () => {
  let id = userStore().user.id
  const res = await http({
    url: '/orders/select/' + id,
    method: 'get'
  })
  if (res.code == 20041) {
    or.value = res.shuju
    console.log(res.shuju);
    status.value = res.shuju.status
    ss.value = true
    let isoString = res.shuju.instime
    createTime.value = new Date(isoString).getTime();
    startCountdown(createTime.value)
  } else {
    uni.showToast({
      title: '没有正在进行的订单',
      icon: 'none',
    });
  }
}
const latitude = ref()
const longitude = ref()
//打卡
const daka = () => {
  haod1e()
}
//向后端发送打卡请求
const dKa = async () => {
  console.log(or.value);
  let ma = {
    latitude: latitude.value,
    longitude: longitude.value,
    sid: or.value.sid,
    id: or.value.id
  }
  const res = await http({
    url: '/orders/ka',
    method: 'POST',
    data: ma
  })
  if (res.code == 20031) {
    uni.showToast({
      title: '打卡成功',
      icon: 'none',
    });
    cha()
  } else {
    uni.showToast({
      title: res.msg,
      icon: 'none',
    });
  }
}
//获取用户当前位置
const haod1e = () => {
  uni.getLocation({
    type: 'wgs84', // 返回的坐标类型，wgs84 表示国际标准的经纬度
    success: function (res) {
      latitude.value = res.latitude;
      longitude.value = res.longitude;
      console.log(latitude.value);
      dKa()
    }
  });
}

const jump = async (obj) => {
  uni.showModal({
    title: '提示',
    content: '确定取消运单吗？',
    success: async (res) => {
      if (res.confirm) {
        up(obj, "取消成功")
      }
    }
  })
}
//修改订单状态
const up = async (obj, msg) => {
  const res = await http({
    url: '/orders/upd/' + or.value.id + '/' + obj,
  })
  if (res.code == 20031) {
    uni.showToast({
      title: msg,
      icon: 'none',
    })
    cha()
  }
}

const getGoodsDetails = async () => {
  //查询货源详情
  const res = await http({
    url: '/orders/selectOrder/' + goodsDetails.value.id,
  })
  console.log(res)
  goodsDetails.value = res.shuju;
};
onShow(() => {
  goodsDetails.value.id=userStore().user.id
  cha()
  getGoodsDetails()
  console.log(or.value);
})
</script>

<style lang="scss" scoped>
.bottom_box {

  position: fixed;
  bottom: 0;
  padding-bottom: env(safe-area-inset-bottom);
  width: 100%;
  // height: 60rpx;
  background-color: #fff;
  display: flex;
  justify-content: space-around;
  align-items: center;

}

/* 保持原有样式不变 */
.container {
}

.top_box {
  font-size: 30rpx;
  color: #fff;
  display: flex;
  justify-content: space-between;
  padding-left: 20rpx;
  padding-right: 20rpx;
  text-align: right;
}

.center_box {
  padding-top: 10rpx;
  display: flex;
  flex-direction: column;
  //justify-content: center;
  align-items: center;
  height: 500rpx;
  font-size: 26rpx;
  font-weight: 700;
  font-weight: 500;
  color: #333
}

.xunh {
  background-color: #FFFFFF;
  padding-left: 30rpx;
  margin-top: 50rpx;
}

.yaodong {
  display: flex;
  padding-top: 20rpx;
}

.fouter_box {
  display: flex;
  margin-top: 20rpx;
  justify-content: space-evenly;
  line-height: 80rpx;
}

.utext {
  font-size: 22rpx;
  color: #333;
  margin-left: 15rpx;
  margin-right: 15rpx;
}


.progress-container {
  background-color: #002f93;
  position: relative;
  height: 200rpx;
  width: 100%;
  padding-top: 15rpx;

}

.status-btn {
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  flex-direction: row;
  align-items: center;
  justify-content: center;
  height: 92rpx;
  margin: 30rpx;
  background-color: #ffffff;
}

.example-body {
  /* #ifndef APP-NVUE */
  display: block;
  /* #endif */
  padding: 15px;
  flex-direction: row;
}
</style>